//
//  LaunchViewController.m
//  yunqiphone
//
//  Created by Irewest on 14-7-24.
//  Copyright (c) 2014年 ci123.com. All rights reserved.
//

#import "LaunchViewController.h"

#define AdAspectRatio   0.695   //广告位宽高比

@interface LaunchViewController ()

@property (nonatomic,retain)NSDictionary *adDic;    //显示的广告数据
@property (nonatomic,retain)NSTimer *adTimer;       //广告显示倒计时
@property (nonatomic,assign)NSInteger timerCount;
@property (nonatomic,retain)UILabel *timerLabel;

@end

@implementation LaunchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)loadView
{
    UIView *view = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    NSString *backImageString = @"Default";
    CGFloat inch = [UIUtils applicationSreenInch];
    if (inch == 4.0) {
        backImageString = @"Default-568h";
    }else if (inch == 4.7) {
        backImageString = @"Default-667h";
    }else if (inch == 5.5) {
        backImageString = @"Default-736h";
    }
    view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:backImageString]];
    self.view = view;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (Current_device_vesion < 7.0) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES
                                                withAnimation:UIStatusBarAnimationNone];
    }
    [self _initView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)_initView
{
    WS(weakSelf);
    
    UIImageView *adImageView = [UIImageView new];
    adImageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:adImageView];
    
    CGFloat bottomHeight = 93.0f;
    NSString *launchWord=@"launch_word.jpg";
    CGFloat inch = [UIUtils applicationSreenInch];
    if (inch == 4.0) {
        bottomHeight = 107.0f;
        launchWord=@"launch_word-568h@2x.jpg";
    }else if (inch == 4.7) {
        bottomHeight = 128.0f;
        launchWord=@"launch_word-667h@2x.jpg";
    }else if (inch == 5.5) {
        bottomHeight = 141.0f;
        launchWord=@"launch_word@3x.jpg";
    }
    [adImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view).insets(UIEdgeInsetsMake(0, 0, bottomHeight, 0));
    }];
    
    _timerCount = 3;//广告倒计时时间 单位：s
    _timerLabel = [UILabel new];
    _timerLabel.backgroundColor = [UIColor whiteColor];
    _timerLabel.font = [UIFont boldSystemFontOfSize:12.0f];
    _timerLabel.textColor = [UIColor blackColor];
    _timerLabel.textAlignment = NSTextAlignmentCenter;
    _timerLabel.hidden = YES;
    _timerLabel.layer.cornerRadius = 7.5f;
    _timerLabel.layer.masksToBounds = YES;
    _timerLabel.text = [NSString stringWithFormat:@"%ld", (long)_timerCount];
    _timerLabel.alpha = 0.7f;
    [adImageView addSubview:_timerLabel];
    [_timerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(-15);
        make.top.equalTo(@15);
        make.width.equalTo(@15);
        make.height.equalTo(@15);
    }];
    
    NSArray *adData = [[NSArray alloc] initWithContentsOfFile:LaunchAdDataListPath] ? : nil;
    if (adData && adData.count > 0) {
        for (NSDictionary *dic in adData) {
            if ([[NSString stringWithFormat:@"%@", dic[@"id"]] integerValue] > 0) {
                NSInteger startTime = [[NSString stringWithFormat:@"%@", dic[@"start_time"]] integerValue];
                NSInteger endTime = [[NSString stringWithFormat:@"%@", dic[@"end_time"]] integerValue];
                
                NSInteger nowTime = [[NSDate date] timeIntervalSince1970];
                
                if (nowTime < startTime || nowTime > endTime) {
                    continue;
                }
                
                NSString *imageKey = @"pic";
                if ([UIUtils applicationSreenInch] == 3.5) {
                    imageKey = @"pic640";
                }
                
                NSString *urlString = [NSString stringWithFormat:@"%@", dic[imageKey]];
                UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:urlString];

                if (image) {
                    adImageView.image = image;
                    if ((dic[@"post_id"] && [dic[@"post_id"] integerValue] > 0) ||
                        (dic[@"url"] && [NSString stringWithFormat:@"%@", dic[@"url"]].length > 5)) {
                        _adDic = dic;
                        adImageView.userInteractionEnabled = YES;
                        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openAdView:)];
                        [adImageView addGestureRecognizer:tap];
                    }
                    break;
                }
            }
        }
    }
    
    if (adImageView.image && (UDfirstLaunch != nil && [UDfirstLaunch isEqualToString:Current_Version])) {
        _timerLabel.hidden = NO;
        _adTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timeCount) userInfo:nil repeats:YES];
    }else {
        adImageView.hidden = YES;
        
        UIImageView *wordImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT-bottomHeight)];
        wordImage.backgroundColor = [UIColor clearColor];
        wordImage.image = [UIImage imageNamed:launchWord];
        //wordImage.alpha = .0f;
        [self.view addSubview:wordImage];
        /*
        [wordImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf.view);
            make.centerY.equalTo(weakSelf.view).offset(-100);
            make.width.equalTo(@210);
            make.height.equalTo(@98);
        }];
        */

        [UIView animateWithDuration:.0f
                           delay:0
                         options:UIViewAnimationOptionCurveEaseInOut
                      animations:^(void){
                          wordImage.alpha = 1.0f;
                      }
                      completion:^(BOOL finished){
                          [self performSelector:@selector(endShowView) withObject:nil afterDelay:2.0f];
                      }];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)endShowView
{
    self.endEvent(_adDic);
}

- (void)timeCount {

    _timerCount--;
    _timerLabel.text = [NSString stringWithFormat:@"%ld", (long)_timerCount];
    
    if (_timerCount < 0) {
        if (_adTimer) {
            [_adTimer invalidate];
            _adTimer = nil;
        }
        _adDic = nil;
        [self endShowView];
        return;
    }
}

- (void)openAdView:(UITapGestureRecognizer *)tap {
    
    if (_adTimer) {
        [_adTimer invalidate];
        _adTimer = nil;
    }

    [self endShowView];
}

@end
